#include "JctoCopyCode.h"
#include <string.h>
#include <malloc.h>

static inline char cmp(const char a[],const char b[])
{
    for(int i=0;a[i];++i)
    {
        if(a[i]!=b[i])
        {
            return 0;
        }
    }
    return 1;
}

void jctoCopyCode(FILE*in,FILE*out,char useCopyFlag)
{
    fseek(in,0,SEEK_END);
    long len=ftell(in);
    fseek(in,0,SEEK_SET);
    char*buf=malloc(len);
    unsigned char flag=0;
    static const char flags[2][30]={"/******JCTO_COPY_START******/","/******JCTO_COPY_STOP******/"};
    fread(buf,1,len,in);
    if(useCopyFlag)
    {
        for(int i=0;i<len;)
        {
            if(cmp(flags[flag],buf+i))
            {
                fwrite(flags[flag],1,strlen(flags[flag]),out);
                i+=strlen(flags[flag]);
                flag=(flag+1)&1;
            }
            else
            {
                if(flag)
                {
                    fwrite(buf+i,1,1,out);
                }
                ++i;
            }
        }
    }
    else
    {
        fwrite(buf,1,len,out);
    }
    free(buf);
}

int jctoCopyReplaceByFile(const char inFile[],const char outFile[],const char flags[2][512],const char file[])
{
    FILE*in=fopen(file,"rb");
    fseek(in,0,SEEK_END);
    long len=ftell(in);
    fseek(in,0,SEEK_SET);
    char*buf=malloc(len+1);
    fread(buf,1,len,in);
    fclose(in);
    buf[len]=0;
    int ans=jctoCopyReplace(inFile,outFile,flags,buf);
    free(buf);
    return ans;
}

int jctoCopyReplace(const char inFile[],const char outFile[],const char flags[2][512],const char code[])
{
    FILE*in=fopen(inFile,"rb");
    fseek(in,0,SEEK_END);
    long len=ftell(in);
    fseek(in,0,SEEK_SET);
    char*buf=malloc(len);
    fread(buf,1,len,in);
    fclose(in);
    FILE*out=fopen(outFile,"wb");
    unsigned char flag=0;
    unsigned int cnt=0;
    for(int i=0;i<len;)
    {
        if(cmp(flags[flag],buf+i))
        {
            if(flag)
            {
                fwrite(code,1,strlen(code),out);
                ++cnt;
            }
            fwrite(flags[flag],1,strlen(flags[flag]),out);
            i+=strlen(flags[flag]);
            flag=(flag+1)&1;
        }
        else
        {
            if(!flag)
            {
                fwrite(buf+i,1,1,out);
            }
            ++i;
        }
    }
    free(buf);
    fclose(out);
    return cnt;
}
